package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.exception.BizException;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.to.OrderLastPriceTo;
import com.atguigu.gulimall.product.vo.SkuInfoItemVo;
import com.atguigu.gulimall.product.vo.SkuItemSaleAttrVo;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        /**
         * key:
         * catelogId: 0
         * brandId: 0
         * min: 0
         * max: 0
         */
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {

            queryWrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            queryWrapper.ge("price", min);
        }

        String max = (String) params.get("max");

        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);

                if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
                    queryWrapper.le("price", max);
                }
            } catch (Exception e) {

            }

        }


        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    //通过spuId 获取skuId
    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = this.baseMapper.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return skuInfoEntities;
    }

    @Override
    public SkuInfoItemVo item(Long skuId) {
        SkuInfoItemVo skuInfoItemVo = new SkuInfoItemVo();
        if (skuInfoItemVo == null) {
            throw new BizException(BizCodeEnume.PRODUCT_PARAM_INVAILD, "所选商品不存在");
        }
        // TODO 1.sku基本信息 接收返回值，后面的异步任务需要用到这个结果
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            skuInfoItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);
        // TODO 6.商品是否有库存，与1无关，与1并列
        CompletableFuture<Void> skuStockFuture = CompletableFuture.runAsync(() -> {
            skuInfoItemVo.setHasStock(1);
        }, executor);
        // TODO 2.此sku的图片集 不需要1的结果，也无返回值，与6并列
        CompletableFuture<Void> skuImageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.listBySkuId(skuId);
            skuInfoItemVo.setImages(skuImagesEntities);
        }, executor);
        // TODO 3.同商品所有销售销售属性及其对应值，需要1的结果 1.thenAcceptAsync
        CompletableFuture<Void> skuSaleAttrFuture = skuInfoFuture.thenAcceptAsync((skuInfoEntity) -> {
            List<SkuItemSaleAttrVo> saleAttrs = skuSaleAttrService.allAttrValueWithSkuBySpuId(skuInfoEntity.getSpuId());
            skuInfoItemVo.setSaleAttr(saleAttrs);
        }, executor);
        // TODO 4.商品描述信息(spu)，需要1的结果，1.thenAcceptAsync，与3并列
        CompletableFuture<Void> spuDescFuture = skuInfoFuture.thenAcceptAsync((skuInfoEntity) -> {
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getBySpuId(skuInfoEntity.getSpuId());
            skuInfoItemVo.setDesp(spuInfoDescEntity);
        }, executor);
        // TODO 5.商品规格参数(spu，属性分组与属性)，需要1的结果，1.thenAcceptAsync，与3,4并列
        CompletableFuture<Void> spuAttrGroupFuture = skuInfoFuture.thenAcceptAsync((skuInfoEntity) -> {
            List<SpuItemAttrGroupVo> itemAttrGroupWithAttrVOS = productAttrValueService.getAttrsWithAttrGroupBySpuId(skuInfoEntity.getSpuId());
            skuInfoItemVo.setGroupAttrs(itemAttrGroupWithAttrVOS);
        }, executor);
        // 等待所有异步任务执行完成,345在1之后执行，所以345完成1肯定完成，不用等1
        try {
            CompletableFuture.allOf(skuStockFuture, skuImageFuture, skuSaleAttrFuture, spuDescFuture, spuAttrGroupFuture).get();
        } catch (Exception e) {
            log.error("线程池异步编排任务失败：{}", e.getCause());
            throw new BizException(BizCodeEnume.THREAD_POOL_TASK_FAILED, "获取商品详情失败");
        }
        return skuInfoItemVo;
    }

    @Override
    public BigDecimal getLastPrice(Long skuId) {
        SkuInfoEntity skuInfoEntity = baseMapper.selectById(skuId);
        BigDecimal price = skuInfoEntity.getPrice();
        return price;
    }

    /**
     * 批量查询价格的方法
     * @param skuIds
     * @return
     */
    @Override
    public List<OrderLastPriceTo> getOrderLaetPrice(List<Long> skuIds) {
        List<SkuInfoEntity> skuInfoEntities = baseMapper.selectBatchIds(skuIds);
        List<OrderLastPriceTo> orderLastPriceTos = skuInfoEntities.stream().map(item -> {
            OrderLastPriceTo orderLastPriceTo = new OrderLastPriceTo();
            orderLastPriceTo.setPrice(item.getPrice());
            orderLastPriceTo.setSkuId(item.getSkuId());
            return orderLastPriceTo;
        }).collect(Collectors.toList());
        return  orderLastPriceTos ;
    }

}